package com.zhou.juc.test09_Interview;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhouyanxiang
 * @create 2020-08-2020/8/15-13:01
 */
public class T03_WithNotifyVolatile {

    volatile List lists = new ArrayList();

    public void add(Object o){
        lists.add(o);
    }

    public int size(){
        return lists.size();
    }

    public static void main(String[] args) {
        T03_WithNotifyVolatile t = new T03_WithNotifyVolatile();
        final Object lock = new Object();

        new Thread(()->{
            synchronized (lock){
                System.out.println(Thread.currentThread().getName() + " start...");
                if (t.size()!= 5){
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + " end...");
            }
        },"t2").start();


        new Thread(()->{
            System.out.println(Thread.currentThread().getName() + " start...");
            synchronized (lock){
                for (int i = 0; i < 10; i++) {
                    t.add(new Object());
                    System.out.println("add " + i);
                    if (t.size() == 5){
                        lock.notify();
                    }
                }

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + " end...");
        },"t1").start();


    }

}
